package com.smzd.framework.system.business;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smzd.core.dao.IDao;
import com.smzd.core.domain.Many2Many;
import com.smzd.framework.core.business.AbstractFGService;
import com.smzd.framework.system.dao.RoleDao;
import com.smzd.framework.system.domain.Role;
import com.smzd.framework.utils.db.FGRowConverter;
import com.smzd.framework.utils.db.RPage;

@Service
public class RoleService extends AbstractFGService<Role> {
	@Autowired
	private RoleDao dao;

	@Override
	protected IDao<Role> getDao() {
		return dao;
	}

	@Override
	public FGRowConverter<Role> getConverter() {
		return RoleService.converter;
	}

	private static FGRowConverter<Role> converter = new FGRowConverter<Role>() {
		@Override
		public Object[] convert(Role elem) {
			Object[] fields = new Object[] { 
					elem.getId(), 
					elem.getName(),
					elem.getValue(),
					elem.getDescription()
			};
			return fields;
		}
	};

	private static FGRowConverter<Role> checkedConverter = new FGRowConverter<Role>() {
		@Override
		public Object[] convert(Role elem) {
			Object[] fields = new Object[] { 
					elem.getId(), 
					elem.getName(),
					elem.getValue(),
					elem.getDescription(),
					elem.getChecked(),
					elem.isDisabled()
			};
			return fields;
		}
	};

	/**
	 * 获取对指定的组进行角色分配时的角色列表
	 * @param page 参数的集合。<br>
	 * <ul>
	 * <li>page.id: 目标权限组的id
	 * <li>page.param1: 登录用户的ID
	 * <li>page.param2: 目标Meeting的ID
	 * </ul>
	 * @param type
	 * @return
	 */
	public String getGroupRoleListDataJson(RPage<Role> page, int type) {
	    switch (type) {
        case 1://meeting0
            dao.getGroupRoleListByPageForMeeting0(page);
            break;
        case 2://owner
            dao.getGroupRoleListByPageForOwner(page);
            break;
        case 3://manager
            dao.getGroupRoleListByPageForManager(page);
            break;
        default:
            break;
        }
		return page.toFlexiGridJsonString(checkedConverter);
	}
	
	public void saveGroupRoles(int groupId, String roleIds) {
		String[] ids = roleIds.split(",");
		List<Many2Many> toAdd = new ArrayList<Many2Many>();
		List<Many2Many> toDel = new ArrayList<Many2Many>();
		for(String id : ids){
			int rid = Integer.parseInt(id);
			Many2Many mm = new Many2Many();
			mm.setKey1(groupId);
			if(rid<0){
				mm.setKey2(-rid);
				toDel.add(mm);
			}else{
				mm.setKey2(rid);
				toAdd.add(mm);
			}
		}
		dao.saveGroupRoles(toAdd, toDel);
	}

}
